import React, {Component} from 'react';
import UserItem from "./userItem.jsx";
import {get_user} from "../../api/api.js";
import PubSub from 'pubsub-js';
import './userList.scss'

class UserList extends Component {
    state = {
        userList: [],
        keyword: '',
    }
    din_yue = null

    componentDidMount() {
        this.din_yue = PubSub.subscribe('搜索', (msg, data) => {
            this.setState({
                keyword: data
            })
            this.dinYueSearch()
        })
    }
    componentWillUnmount() {
        console.log('取消订阅')
        PubSub.unsubscribe(this.din_yue)
    }

    //订阅搜索事件
    dinYueSearch(keyword) {
        get_user(keyword).then(da => {
            this.setState({
                userList: da
            })
        })
    }

    render() {
        return (
            <>
            {
                this.state.keyword === '' ? '' : <div className={"keyword-title"}>搜索关键词：{this.state.keyword}</div>
            }
                <div className={"user-list"}>
                    {this.state.userList.map(user => <UserItem key={user.id} userInfo={user}/>)}
                </div>
            </>
        );
    }
}

export default UserList;